import { parse } from 'qs'
import { message } from 'antd'
import { isEmpty, cloneDeep } from 'lodash'
import { Link, hashHistory } from 'dva/router'
import {
	getDetail,
	addRole,
	editRole,
	getResource,
	getAppList
} from './sectionInfoServ'
import AppBus from '../../../../utils/bus'
import config from '../../../../config/config'

//从列表中筛选出子节点和非子节点
const filterTreeNodeFromList = (list) => {
	let leafNode = [], halfNode = [];
	if (list == null) {
		return {
			checkedKeys: leafNode,
			halfCheckedKeys: halfNode
		}
	}
	for (let i = 0; i < list.length; i++) {
		let temp = cloneDeep(list);
		let select = temp.splice(i, 1);
		let flag = false;				//是不是有子节点指向select
		temp.forEach((item, index) => {
			if (item.parentId == select[0].id) {
				flag = true;
			}
		});
		if (!flag) { leafNode.push((select[0].id).toString()) }
	}

	list.forEach((item, index) => {
		//leafNode没有的，就说明是非子节点
		if (leafNode.indexOf((item.id).toString()) == -1) {
			halfNode.push((item.id).toString());
		}
	})

	return {
		checkedKeys: leafNode,
		halfCheckedKeys: halfNode
	}
}

const detail = {
	id: '',
	name: '',
	description: '',
	applicationId: '',
	resourceList: [],
}

const defaultState = {
	detail: cloneDeep(detail),
	//角色资源树
	roleTree: [],
	//应用列表
	appList: [],
	//'add' or 'edit'
	type: '',
	//被选中的资源树id
	checkedKeys: [],
	halfCheckedKeys: [],

};

const roleInfoModel = {
	state: cloneDeep(defaultState),
	//订阅数据
	subscriptions: {
		setup({ dispatch, history }) {
			return history.listen(location => {
				if (location.pathname == roleInfoModel.pathname) {
					dispatch({ type: 'valueNull' });
					if (location.query.type == 'edit') {
						dispatch({ type: 'app/setTabTitle', payload: { title: '角色编辑', location } });
					} else {
						dispatch({ type: 'app/setTabTitle', payload: { title: '角色新增', location } });
					}
					dispatch({ type: 'init', payload: location.query });
				}
			})
		},
	},
	effects: {
		* init({ payload }, { call, put, select }) {
			let state = yield select(e => e[namespace]);
			yield put({ type: 'store', payload: { type: payload.type } });
			yield put({ type: 'getResource' });
			yield put({ type: 'getAppList' });
			if (payload.type == 'add') {
			} else {
				yield put({ type: 'getDetail', payload: { id: payload.id } });
			}
		},

		*valueNull({ payload }, { put, call, select }) {
			yield put({ type: 'store', payload: cloneDeep(defaultState) });
		},

		*updateModel({ payload: obj }, { put, call, select }) {
			yield put({ type: 'store', payload: { ...obj } });
		},

		*getDetail({ payload }, { put, call, select }) {
			let state = yield select(e => e[namespace]);
			try {
				let { data, resultCode } = yield call(getDetail, { id: payload.id });
				if (resultCode == 0) {
					if (!data) { return }
					// let checkedKeys = [];
					// data.resList && data.resList.forEach((e, i) => { checkedKeys.push(String(e.id)) })
					let nodeObj = filterTreeNodeFromList(data.resList);
					yield put({ type: 'store', payload: { detail: data, checkedKeys: nodeObj.checkedKeys, halfCheckedKeys: nodeObj.halfCheckedKeys } });
				}
			} catch (error) {
				console.error(error);
			}
		},

		*getResource({ payload }, { put, call, select }) {
			let state = yield select(e => e[namespace]);
			try {
				let { data, resultCode } = yield call(getResource);
				if (resultCode == 0) {
					if (!data) { return }
					yield put({ type: 'store', payload: { roleTree: data } });
				}
			} catch (error) {
				console.error(error);
			}
		},

		*getAppList({ payload }, { put, call, select }) {
			try {
				let { data, resultCode } = yield call(getAppList);
				if (resultCode == 0) {
					let state = yield select(e => e[namespace]);
					let detail = state.detail;
					if (!data) { return }
					if (data.length != 0) {
						detail = Object.assign({}, detail, { applicationId: String(data[0].id) })
					}
					if (state.type == 'add') {
						yield put({ type: 'store', payload: { appList: data, detail: detail } });
					} else {
						yield put({ type: 'store', payload: { appList: data } });
					}
				}
			} catch (error) {
				console.error(error);
			}
		},

		*save({ payload }, { put, call, select }) {
			let state = yield select(e => e[namespace]);
			try {
				if (state.type == 'add') {
					let param = {
						name: String(state.detail.name).trim(),
						description: state.detail.description,
						applicationId: state.detail.applicationId,
						resIds: state.checkedKeys.concat(state.halfCheckedKeys).join(','),
					}
					let { data, resultCode } = yield call(addRole, param);
					if (resultCode == 0) {
						message.success('新增成功');
						// AppBus.emit('closeTab', {
						// 	key: MODULE_TO_ROUTES[namespace].urlArray[1],
						// 	cbf: () => {
						hashHistory.push(MODULE_TO_ROUTES[namespace].urlArray[0]);
						// 	}
						// })
					}
				} else {
					let param = {
						name: state.detail.name,
						description: state.detail.description,
						applicationId: state.detail.applicationId,
						resIds: state.checkedKeys.concat(state.halfCheckedKeys).join(','),
						id: state.detail.id,
						status:state.detail.status
					}
					let { data, resultCode } = yield call(editRole, param);
					if (resultCode == 0) {
						message.success('保存成功');
						// AppBus.emit('closeTab', {
						// 	key: MODULE_TO_ROUTES[namespace].urlArray[1],
						// 	cbf: () => {
						hashHistory.push(MODULE_TO_ROUTES[namespace].urlArray[0]);
						// 	}
						// })
					}
				}
			} catch (error) {
				console.error(error);
			}
		},

	},
	reducers: {
		store(preState, action) {
			return Object.assign({}, preState, action.payload);
		}
	}
}
export default roleInfoModel
